<?php

namespace app\api\model;
use think\Db;

class UserClaimAddress extends Common {
    /**
     * @param $address_id
     * @param $user_id
     */
    public static function sendredpacket($address_id, $user_id, $source_type = 0, $source_id = 0) {
        try {
            $timenow       = time();
            $AddRedpackets = Db::name('user_address_red_packet')
                ->where([
                    'address_id'  => $address_id,
                    'stock'       => ['>', 0],
                    'status'      => 0,
                    'paystate'    => 1,
                    'expire_time' => ['>', $timenow],
                ])
                ->field('id,address_id,type,price,stock,expire_time')
                ->select();
            foreach ($AddRedpackets as $key => $value) {
                // 今日已获取该红包
                $todayGeted = Db::name('user_address_redpacket_records')->where(['address_redpacket_id' => $value['id'], 'user_id' => $user_id])->whereTime('time', 'today')->count();
                if ($todayGeted) {
                    continue;
                }
                // 发放
                Db::name('user_address_red_packet')->where(['id' => $value['id']])->setDec('stock');
                switch ((int) $value['type']) {
                case 1:
                    Db::name('user_coupon')->insert([
                        'user_id'     => $user_id,
                        'price'       => $value['price'],
                        'data'        => '',
                        'address_id'  => $value['address_id'],
                        'expire_time' => $value['expire_time'],
                        'create_time' => $timenow,
                    ]);
                    Privatechat::notice($user_id, 'Flag打卡获得优惠券 「' . $value['price'] . '元」 ，已转入您的账户');
                    break;
                case 2:
                    VolleyDesc::index($user_id, $value['price'], '地点[ID: ' . $value['address_id'] . ']打卡', 1);
                    Privatechat::notice($user_id, 'Flag打卡获得 「' . $value['price'] . '金币」 ，已转入您的账户');
                    break;
                case 3:
                    YaoqingRecords::index($user_id, 0, $value['price'], '地点[ID: ' . $value['address_id'] . ']打卡', 1);
                    Privatechat::notice($user_id, 'Flag打卡获得 「' . $value['price'] . '积分」 ，已转入您的账户');
                    break;
                }
                Db::name('user_address_redpacket_records')->insert([
                    'address_redpacket_id' => $value['id'],
                    'user_id'              => $user_id,
                    'type'                 => $value['type'],
                    'price'                => $value['price'],
                    'time'                 => $timenow,
                    'source_type'          => $source_type,
                    'source_id'            => $source_id,
                ]);
            }
        } catch (\Exception $e) {

        }
    }
    public static function getredpacket($address_id, $user_id) {
        $redpackets = ['volley'=>0,'score'=>0,'coupon'=>0];
        try {
            $timenow       = time();
            $AddRedpackets = Db::name('user_address_red_packet')
                ->where([
                    'address_id'  => $address_id,
                    'stock'       => ['>', 0],
                    'status'      => 0,
                    'paystate'    => 1,
                    'expire_time' => ['>', $timenow],
                ])
                ->field('id,address_id,type,price,stock,expire_time')
                ->select();
            foreach ($AddRedpackets as $key => $value) {
                // 今日已获取该红包
                $todayGeted = Db::name('user_address_redpacket_records')->where(['address_redpacket_id' => $value['id'], 'user_id' => $user_id])->whereTime('time', 'today')->count();
                if ($todayGeted) {
                    continue;
                }
                switch ((int) $value['type']) {
                case 1:
                    $redpackets['coupon'] = $value['price'];
                    break;
                case 2:
                    $redpackets['volley'] = $value['price'];
                    break;
                case 3:
                    $redpackets['score'] = $value['price'];
                    break;
                }
            }
        } catch (\Exception $e) {

        }
        return $redpackets;
    }

    /**
     * @param $params
     * @return mixed
     */
    public static function FindByCreate($params) {
        $data = self::get(['name' => $params['name'], 'address' => $params['address']]);
        if ($data) {
            return $data->id;
        } else {
            if (!$params['name'] || !$params['address'] || !$params['longitude'] || !$params['latitude'] || !$params['city']) {
                return 0;
            }
            $pattern = '/\d+米/'; // 匹配形如（50米）的字符串，\d+匹配1个或多个数字
            if (preg_match($pattern, $params['name'])) {
                return 0;
            }
            if (strpos($params['name'], '附近') !== false) {
                return 0;
            }

            $params['update_time'] = $params['create_time'] = time();
            $params['user_id']     = 0;
            $params['state']       = 1;
            $data                  = self::create($params);
            return $data->id;
        }
    }
    public static function FindByArea($longitude, $latitude) {
        $model = new UserClaimAddress;
        $data = $model->where(['longitude'=>$longitude, 'latitude'=>$latitude])->find();
        if (!$data) {
            $array = self::returnSquarePoint($longitude, $latitude, 0.01);
            $map = array(
                'latitude' => array(array('EGT',$array['right-bottom']['lat']),array('ELT',$array['left-top']['lat']),'and'),
                'longitude' => array(array('EGT',$array['left-top']['lng']),array('ELT',$array['right-bottom']['lng']),'and'),
            );
            $data = $model->where($map)->find();
        }
        return $data ? $data['id'] : 0;
    }

      /*
      *参数说明：
      *$lng  经度
      *$lat   纬度
      *$distance  周边半径  默认是500米（0.5Km）
      */
     public static function returnSquarePoint($lng, $lat,$distance = 0.5) {
         $dlng =  2 * (($distance / (2 * 6371)) / (($lat)));
         $dlng = ($dlng);
         $dlat = $distance/6371;//地球半径，平均半径为6371km
         $dlat = ($dlat);
 
         return array(
             'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
             'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
             'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
             'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
         );
 
     }
}
